package com.weishuang.monitor.leader.config.client;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ClientAbstractAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {

    private static final String id = "clientId";
    private static final String secret = "clientSecret";

    /**
     * 为检测端提供认证接口
     */
    protected ClientAbstractAuthenticationProcessingFilter() {
        super(new AntPathRequestMatcher("/api/authentication","POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
        String clientId = httpServletRequest.getParameter(id);
        String clientSecret = httpServletRequest.getParameter(secret);
        if (StringUtils.isNotBlank(clientId)) {
            clientId = clientId.trim();
        }
        if (StringUtils.isNotBlank(clientSecret)) {
            clientSecret = clientSecret.trim();
        }
        ClientAuthenticationToken authenticationToken = new ClientAuthenticationToken(clientId,clientSecret);
        return this.getAuthenticationManager().authenticate(authenticationToken);
    }
}
